# coding:utf-8
from ftplib import FTP

FTP_URL = 'FTP://'
FTP_USER = 'U'
FTP_PASSWORD = 'P'

ftp = None


def login():
    global ftp
    ftp = FTP('ftp.us.debian.org')
    ftp.login()
    print('logged in')
    ftp.cwd('debian')  # 根据需要看是否需要调用切换服务器当前文件夹
    return ftp


# config_ext = '.config'
config_ext = '.gz'


def browse_ftp_files():
    files = ftp.nlst('.')
    print(files)
    return files


def download_file(src_name):
    '''
    下载某个文件到本地，为了方便，默认源文件名和目标文件名一样，下载后的文件在py文件旁边
    :param src_name: ftp上的文件的文件名
    :return:
    '''
    print(f'下载了{src_name}')
    pass


def extract_excel_extensions(excel_file_name='List.xlsx'):
    '''
    从excel提取扩展名，可用openpyxl库，如果数据是规范的二维表结构可以考虑pandas库
    :param excel_file_name: 默认值是'List.xlsx'
    :return:
    '''
    return ['txt', 'doc']


def get_first_config_file_name(src_files):
    '''
    获取第一个config文件
    :param src_files:
    :return:
    '''
    print(f'正在查找扩展名为{config_ext}的文件...')
    config_file = next(f for f in src_files if f.endswith(config_ext))
    print(f'找到{config_file}')
    return config_file.replace(config_ext, '')  # 获取了xxxx


if __name__ == "__main__":
    login()
    src_files = browse_ftp_files()
    print(src_files)
    excel_file_name = 'List.xlsx'
    download_file(excel_file_name)
    excel_extensions = extract_excel_extensions(excel_file_name)
    xxx = get_first_config_file_name(src_files)
    for ext in excel_extensions:
        src_file = f'{xxx}.{ext}'
        print(f'正在下载{src_file}')
        download_file(src_file)
    ftp.quit()
